﻿from django.db import models
from django.db.models.signals import post_save, post_delete
from django.core.cache import cache
from userprofile.models import UserProfile

class PrivateMessage(models.Model):
        
        
    sender = models.ForeignKey(UserProfile, related_name='message_sender',  verbose_name=u'от кого', null=False, blank=True)
    receiver = models.ForeignKey(UserProfile, related_name='message_receiver', verbose_name=u'кому', null=False, blank=True)
    subject = models.CharField(u'заголовок', max_length=150, null=True, blank=True)
    text = models.TextField(u'текст сообщения')
    date = models.DateTimeField(u'дата отправления', auto_now_add=True)
    is_read = models.BooleanField(u'прочитано', default=False)
        
    def __unicode__(self):
        return unicode(self.subject)
      
    def get_count(to_id):
        cache_key = 'new_messages_count_for_%s' % (to_id)
        count = cache.get(cache_key)
        if count is None:
            from django.db import connection
            table_name = str(PrivateMessage._meta.db_table)
            query = 'SELECT COUNT(id) FROM %s WHERE (%s.is_read = 0 AND %s.receiver_id = %s )' % (table_name, table_name, table_name, str(to_id))
            cursor = connection.cursor()
            cursor.execute(query)
            count = cursor.fetchone()
            cache.set(cache_key, count)
        return count
    get_count = staticmethod(get_count)
          
    class Meta:
        verbose_name = u'сообщение'
        verbose_name_plural = u'сообщения'


def nuke_count(self, instance, **kwargs):
    cache_key = 'new_messages_list_for_%s' % (self.receiver.pk)
    cache.delete(cache_key)
    
post_save.connect(nuke_count, PrivateMessage)
post_delete.connect(nuke_count, PrivateMessage)